<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>超时与取消请求</title>
</head>
<body>
    <button>发送请求</button>
    <button>取消请求</button>
    <script>
        //  GET   http://127.0.0.1:8080/search
        let btns = document.querySelectorAll('button');
        let xhr = null;
        //第一个按钮
        btns[0].onclick = function(){
            //如果 xhr 为对象, 则取消上一个请求
            if(xhr) {
                xhr.abort();
            }
            xhr = new XMLHttpRequest();
            //设置超时时间  2000
            // xhr.timeout = 2000;
            // //设置超时回调
            // xhr.ontimeout = function(){
            //     alert('请求超时, 请稍后再试~~~');
            // }
            xhr.open('get', 'http://127.0.0.1:8080/search')
            xhr.send();
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    //控制台输出响应体
                    console.log(xhr.response);
                }
            }
        }

        //第二个按钮 单击事件   xhr.abort();
        btns[1].onclick = function(){
            //判断
            if(!xhr) return; 
            xhr.abort();
        }
    </script>
</body>
</html>